<template>

    <!-- 导航栏 -->
    <van-sticky>
        <van-nav-bar
            title="购物车"
            left-text="返回"
            left-arrow
            placeholder
            @click-left="onBack"
            v-if="action === 'info'"
        />

        <van-nav-bar
            title="购物车"
            placeholder
            v-else
        />
    </van-sticky>
    <van-checkbox-group v-model="CheckedArr" @change="onChange" ref="CheckboxGroup">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
                v-model:loading="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
            >
                <div class="cart" v-for="(item,index) in CartList" :key="item.id">
                    <van-checkbox :name="item.id"></van-checkbox>

                    <!-- 滑动单元格 -->
                    <van-swipe-cell>
                        <!-- 商品卡片 -->
                        <van-card
                            :thumb="item.products.thumbs_cdn"
                           
                            @click-thumb="ToProductInfo(item.products.id)"
                        >
                            <template #title>
                                <div class="title"  @click="ToProductInfo(item.products.id)">{{ item.products.name }}</div>
                            </template>

                            <!-- 卡片的插槽部分 -->
                            <template #desc>
                                <van-tag class="tag" type="danger" v-if="!item.attrs">暂无商品规格</van-tag>
                                <div v-else>
                                    <van-tag class="tag" type="primary" v-for="attr in JSON.parse(item.attrs)">{{ attr.value }}</van-tag>
                                </div>
                            </template>

                            <template #tags>
                                <div class="price">单价：￥{{ item.price }}</div>
                            </template>

                            <template #price>
                                <div class="price">合计：￥ {{ item.total }}</div>
                            </template>

                            <!-- 卡片的商品数量 步进器 -->
                            <template #num>
                                <van-stepper 
                                v-model="item.nums" 
                                theme="round"
                                min="1" 
                                :max="item.products.stock"
                                :name="index"
                                @change="onUpdateStock" />
                            </template>
                        </van-card>

                        <!-- 滑动单元格插槽 右侧滑动 -->
                        <template #right>
                            <van-button square text="删除" type="danger" class="delete-button" @click="onDel(item.id,index)" />
                        </template>

                    </van-swipe-cell>
                </div>
            </van-list>
        </van-pull-refresh>
 <!-- 提交动作栏 -->
 <van-submit-bar :price="total" :class="action === 'info' ? '' : 'bottom50'" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="CheckedAll" @change="onCheckedAll" :indeterminate="isIndeterminate">全选</van-checkbox>
    </van-submit-bar>
        
    </van-checkbox-group>
    <Tabbar v-if="!action" />
</template>

<script setup>

const { proxy } = getCurrentInstance();

const action = ref(proxy.$route.query.action ?? '');
const business = proxy.$business;
const CartList =ref([]);
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const CheckedArr = ref([]);
const page = ref(1);

const isIndeterminate = ref(false);
const CheckboxGroup = ref(null);
const CheckedAll = ref(false);

const onRefresh = () =>
{
    CartList.value = [];
    page.value = 1;
    refreshing.value = true;
    finished.value = false;
    loading.value = true;

    setTimeout(onLoad,1500);
}

const onLoad = async () =>
{

    if(refreshing.value === true)
    {
        refreshing.value = false;
    }

    let params = {
        busid:business.value.id,
        page:page.value
    }

    let result = await proxy.$http.post({
        url:'/cart/index',
        params
    })

    finished.value = false;
    loading.value = false;

    if(result.code === 1)
    {
        let count = result.data.count ?? 0;
        CartList.value = CartList.value.concat(result.data.list);

        if(CartList.value.length == count)
        {
            finished.value = true;

            return false;
        }

        page.value = page.value + 1;

    }else{
        finished.value = true;
        proxy.$fail(result.msg);
    }

}

const onChange = (name) =>
{
    CheckedAll.value = CheckedArr.value.length === CartList.value.length
    console.log("🚀 ~ CheckedAll.value:", CheckedAll.value)
    isIndeterminate.value = CheckedArr.value.length > 0 && CheckedArr.value.length < CartList.value.length
    console.log("🚀 ~ isIndeterminate.value:", isIndeterminate.value)
}
const onCheckedAll = (value) =>
{
    CheckboxGroup.value.toggleAll(value);
}

const total = computed(() =>
{
    let total = 0;

    if(CheckedArr.value.length > 0)
    {
        CartList.value.map(item => {
            if(CheckedArr.value.includes(item.id))
            {
                total += parseFloat(item.total)
            }

        })
        
    }
    return total * 100 ;
})
    
       

const onDel = (cartid,index) =>
{
    proxy.$confirm({
        title:'删除',
        message:'是否确认删除该记录？'
    }).then(async () => {
        let params = {
            cartid,
            busid:business.value.id
        }

        let result = await proxy.$http.post({
            url:'/cart/del',
            params
        })

        if(result.code === 1)
        {
            proxy.$showSuccessToast({
                message:result.msg,
                onClose:() =>
                {
                    CartList.value.splice(index,1);
                }
            })
        }else{
            proxy.$fail(result.msg);
        }


    }).catch((err) => {});
}

const onUpdateStock = async (value,{ name }) => 
{
     
        let params = {
            cartid:CartList.value[name].id,
            nums:value,
            busid:business.value.id
        }
        let result = await proxy.$http.post({
            url:'/cart/stock',
            params
        })
        if(result.code === 1)
        {
            CartList.value[name].total = (parseFloat(CartList.value[name].price) * value).toFixed(2); 
            console.log("🚀 ~ CartList:", CartList)
        }else{
            proxy.$fail(result.msg);
        }
    
}


const onSubmit = () =>
{
    if(CheckedArr.value.length === 0)
    {
        proxy.$fail('请选择结算商品');

        return false;
    }
    
    let cartids = CheckedArr.value.join(',');

    proxy.$router.push({path:'/order/confirm',query:{cartids:cartids}});
}


const ToProductInfo = (proid) => proxy.$router.push({path:'/product/info',query:{proid}});

const onBack = () => proxy.$router.back();
</script>

<style scoped>
@import url('/assets/css/cart.css');

.bottom50{
    bottom: 50px;
}
</style>